import React, { useState, useRef,useEffect } from 'react';
import { message,Form,Card,Tooltip,Popconfirm } from 'antd';
import {
    CloseOutlined, PlusOutlined,
  } from '@ant-design/icons';
import { connect } from 'dva';
import { del,save } from './service';
import GdWageForm from './gdWageForm';
import {HasPermission} from '@/components/AuthComponent/HasPermission';
const AuthPlus = HasPermission(PlusOutlined);
const AuthDel = HasPermission(CloseOutlined);
const GdWage = props => {
    const { submitting,dispatch } = props
    const [_gdWageList, setGdWageList] = useState([]);
    const [form] = Form.useForm();
    useEffect(() => {
        if (dispatch) {
          dispatch({
            type: 'cubeWage/gdWageList',
            payload:{}
          }).then((result)=>{
            setGdWageList(result)
          })
         }
       }, []);
    /**
     * 保存
     * @param {*} values 
     */
    const onFinish =async (values,item) =>{
        const hide = message.loading('正在保存');
        if(item.id){
            values.id= item.id;
        }
        try {
          await save({
            ...values,
            salaryType:1
          });
          hide();
          message.success('保存成功');
          return true;
        } catch (error) {
          hide();
          message.error('保存失败，请重试');
          return false;
        }
    }
    /**
     * 删除
     */
    const delGdWage = async (item,index) =>{
        if(!item.id||item.id==''){
            //直接删除
            _gdWageList.splice(index,1)
            setGdWageList([..._gdWageList]);
            return;
        }
        const hide = message.loading('正在删除');
        try {
          let result = await del({
            id: item.id,
          });
          hide();
          if(result.code==0){
            message.success('删除成功，即将刷新');
            _gdWageList.splice(index,1)
            setGdWageList([..._gdWageList]);
            return true;
          }else{
            message.success(result.message);
            return false;
          }
        } catch (error) {
          hide();
          message.error('删除失败，请重试');
          return false;
        }
    }
  /**
   * 新增固定工资
   */
  const addGdWage = () =>{
    setGdWageList([..._gdWageList,{}])
  }
    return <Card title="固定工资" extra={<Tooltip placement="top" title="增加"><AuthPlus auth={[`wage:gd:add`]} onClick={addGdWage}/></Tooltip>}>
        {
            _gdWageList&&_gdWageList.map((item,index)=>
            <Card style={{marginBottom:32}} type="inner" size="small"  key={index}  extra={<Popconfirm
              title="确认删除?"
              onConfirm={()=>delGdWage(item,index)}
            ><AuthDel auth={[`wage:gd:delete`]}/></Popconfirm>}>
            <GdWageForm onFinish={onFinish} item={item} submitting={submitting}/>
        </Card>)
        }
  </Card>
}
export default connect(({ loading,cubeWage }) => ({
    submitting: loading.effects['cubeWage/save'],
    gdWageList: cubeWage.gdWageList
}))(GdWage);